<template>
  <div class="add-or-edit-section">
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="120px"
      class="demo-form"
    >
      <el-form-item label="课程名称" required>
        <el-input disabled v-model="form.courseName"></el-input>
      </el-form-item>
      <el-form-item label="章节名称" prop="sectionName">
        <el-input v-model="form.sectionName"></el-input>
      </el-form-item>
      <el-form-item label="章节描述">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input type="number" v-model="form.orderNum">
          <template slot="append">数字控制排序，数字越大越靠后</template>
        </el-input>
      </el-form-item>
      <el-form-item class="action">
        <el-button @click="$emit('sectionCancel')">取消</el-button>
        <el-button @click="submitForm('form')" type="primary">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { saveOrUpdateSection, getBySectionId } from '@/service/lesson'
export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    courseName: {
      type: String
    },
    sectionId: {
      type: [String, Number]
    }
  },
  data () {
    return {
      form: {
        courseId: 0,
        courseName: '',
        sectionName: '',
        description: '',
        orderNum: 0
      },
      rules: {
        sectionName: [
          { required: true, message: '请输入章节名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    sectionId (newValue) {
      newValue && this.loadSection()
    }
  },
  methods: {
    async loadSection () {
      const { data } = await getBySectionId({
        sectionId: this.sectionId
      })
      if (data.code === '000000') {
        this.form = data.data
      }
      this.form = Object.assign(this.form, { courseName: this.courseName })
    },
    async submitForm (formName) {
      try {
        const valid = await this.$refs[formName].validate()
        if (valid) {
          const { data } = await saveOrUpdateSection(this.form)
          if (data.code === '000000') {
            this.$message.success('保存成功')
            this.$emit('sectionSuccess')
          }
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.action ::v-deep .el-form-item__content {
  text-align: right;
}
</style>
